<template>
  <div>
    <h4>基本信息</h4>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="text-align: left">
      <el-form-item label="供应商" style="font-weight: bold">
        <el-select size="mini" v-model="searchForm.supplierId" placeholder="供应商名称">
          <el-option v-for="(item,index) in supList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单日期" style="font-weight: bold">
        <el-date-picker
            size="mini"
            v-model="searchForm.purchaseDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item style="font-weight: bold">
        <el-button size="mini" style="float: left;margin-left: 15px;margin-top: 6px" @click="getPurPage"
                   type="primary" icon="el-icon-zoom-in" plain>查找
        </el-button>
        <el-button size="mini" style="float: left;margin-left: 15px;margin-top: 6px" @click="resetSearch"
                   type="warning" icon="el-icon-refresh" plain>重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-button size="mini" style="float: left" type="success" icon="el-icon-plus" plain @click="toSave">新增</el-button>
    <h4>采购订单信息</h4>
    <el-table
        v-loading="loading"
        :data="purTable"
        style="width: 100%">
      <el-table-column
          align="center"
          prop="id"
          label="订单ID"
          width="90">
      </el-table-column>
      <el-table-column
          align="center"
          prop="sname"
          label="供应商"
          width="130"
      >
      </el-table-column>
      <el-table-column
          align="center"
          prop="createdAt"
          label="下单日期"
          width="120">
      </el-table-column>
      <el-table-column label="状态" width="90" align="center">
        <el-tag type="success">{{ '审核通过' }}</el-tag>
      </el-table-column>
      <el-table-column
          align="center"
          prop="totalAmount"
          label="总金额"
          width="100">
      </el-table-column>
      <el-table-column
          align="center"
          label="订单明细">
        <template slot-scope="scope">
          <table align="center">
            <tr>
              <th>序号</th>
              <th>商品名称</th>
              <th>单价</th>
              <th>份数</th>
              <th>小计（元）</th>
            </tr>
            <tr v-bind:key="index" v-for="(detail,index) in scope.row.purchaseDetailsList">
              <td>{{ index + 1 }}</td>
              <td>{{ detail.prName }}</td>
              <td>{{ detail.price }}</td>
              <td>{{ detail.quantity }}</td>
              <td>{{ detail.quantity * detail.price }}</td>
            </tr>
          </table>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="操作">
        <template slot-scope="scope">
          <el-link icon="el-icon-delete" @click="delPur(scope.row.id)" id="delBut" :underline="false">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :page-size="5"
        :pager-count="11"
        @current-change="nextPage"
        layout="prev, pager, next"
        :total="this.searchForm.total">
    </el-pagination>

    <!--  新增-->
    <el-dialog
        :destroy-on-close="true"
        title="添加商品"
        :visible.sync="purFormDialog"
        width="30%">
      <el-form :model="purForm" ref="purForm" :rules="rules" style="text-align: left;margin-left: 70px">
        <el-form-item label="供应商" style="font-weight: bold" prop="supplierId">
          <el-select size="small" v-model="purForm.supplierId" placeholder="供应商名称" @change="getProduct()">
            <el-option v-for="(sup,index) in supList" :key="index" :label="sup.name" :value="sup.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品列表" style="font-weight: bold;" prop="productId">
          <el-select  v-model="purForm.productId" multiple placeholder="请选择" size="small">
            <el-option
                v-for="item in proList"
                :key="item.id"
                @click.native="showSlider(item)"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <div class="block" v-for="(pur,index) in pList" v-bind:key="index" style="margin-bottom: 5px">
            {{ pur.productName }}
            <el-input-number v-model="pur.quantity" :min="1" :max="pur.stockQuantity">{{ pur.name }}</el-input-number>
            <input type="hidden" v-model="pur.price">
          </div>
        </el-form-item>
        <el-form-item label="下单日期" style="font-weight: bolder" prop="purchaseDate">
          <el-date-picker
              v-model="purForm.purchaseDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="purFormDialog=false">取消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>


import {addPurchases, delPurchases, getAddSupplier, getPage, getSupplier} from "@/api/purchases";


export default {
  name: 'PurchaseView',
  data() {
    return {
      loading: true,
      supList: [],
      searchForm: {
        supplierId: '',
        purchaseDate: '',
        pageNow: 1,
        total: 0
      },
      purTable: [],
      purFormDialog: false,
      purForm: {
        purchaseId: 0,
        supplierId: '',
        productId: '',
        purchaseDate:'',
      },
      proList: [],
      pList: [],
      inboundAddDto:{
        purchaseId:0,
        receivedDate:''
      },
      rules: {
        supplierId: [
          {required: true, message: '供应商必填', trigger: 'blur'},
        ],
        productId: [
          {required: true, message: '必须选择一个商品', trigger: 'blur'},
        ],
        purchaseDate: [
          {required: true, message: '请选择下单日期', trigger: 'blur'},
        ],
      },
    }
  },

  methods: {
    //单个删除
    delPur(purId) {
      this.$confirm('此操作将永久删除该采购订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPurchases(purId).then((res)=>{
          if(res.code==200){
            this.$message.success("删除成功")
            this.getPurPage();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //提交表单，新增
    submitForm() {
      this.$refs["purForm"].validate(valid => {
        if (valid) {
          if (this.purForm.purchaseId == 0) {
            this.purForm.detailsDtoList = this.pList
            addPurchases(this.purForm).then((res) => {
              if (res.code == 200) {
                this.$message.success("操作成功")
                this.getPurPage();
                this.purFormDialog=false;
              }
            })
          }
        }
      })
    },
    showSlider(t) {
      setTimeout(() => {
        let s = '';
        for (let i = 0; i < this.pList.length; i++) {
          s += '[' + this.pList[i] + ']';
        }
        console.log(s)
        if (s.indexOf('[' + t.id + ']') == -1) {
          let o = {productId: t.id, productName: t.name, quantity: '', price: t.purchasingPrice};
          this.pList.push(o)
        }
      }, 200)
    },
    //获得指定的供应商手下的商品
    getProduct() {
      getAddSupplier(this.purForm.supplierId).then((res) => {
        if (res.code == 200) {
          this.proList = res.data
        }
      })
    },
    //打开新增弹窗
    toSave() {
      this.purFormDialog = true;
    },
    // 表格翻页
    nextPage(val) {
      this.searchForm.pageNow = val;
      this.getPurPage();
    },
    // 重置查询选项
    resetSearch() {
      this.searchForm = {
        supplierId: '',
        purchaseDate: '',
        pageNow: 1
      }
    },
    //查询所有数据并设置分页
    getPurPage() {
      getPage(this.searchForm).then((res => {
        if (res.code == 200) {
          console.log(res.data)
          this.purTable = res.data.records;
          this.searchForm.total = res.data.total;
          this.loading = false;
        }
      }))
    },
    //获得查询选项里的供应商列表
    getSupplierList() {
      getSupplier().then((res) => {
        if (res.code == 200) {
          this.supList = res.data
        }
      })
    }
  },
  mounted() {
    this.getSupplierList();
    this.getPurPage();
  },
};
</script>

<style>
#delBut:hover {
  color: red;
}
</style>